﻿using System;

namespace Carbon.Web.Forms
{
    public class FormsContext : IDisposable
    {
		#region Fields (3)
		private IPersistanceService m_PersistanceService = default(IPersistanceService);

		private bool m_Diposed = false;
		private bool m_PersistanceService_calculated = false;
		#endregion

		#region Properties (2)
		public static FormsContext Current
        {
            get
            {
                FormsContext context = DisposeHttpModule.GetThreadObject<FormsContext>();

                if (context == null)
                {
                    context = new FormsContext();
                    DisposeHttpModule.SetThreadObject<FormsContext>(context);
                }

                return context;
            }
        }
		public IPersistanceService PersistanceService
        {
            get
            {
                if (!m_PersistanceService_calculated)
                {
                    Type persistanceServiceFactoryType = Configuration.Instance.PersistanceServiceFactoryTypeInstanted;
                    using (IPersistanceServiceFactory persistanceServiceFactory = (IPersistanceServiceFactory)Activator.CreateInstance(persistanceServiceFactoryType))
                    {
                        m_PersistanceService = persistanceServiceFactory.CreatePersistanceService();
                        m_PersistanceService_calculated = true;
                    }
                }

                return m_PersistanceService;
            }
        }
		#endregion

		#region Methods (1)

		public void Dispose()
        {
            if (m_Diposed) throw new NotSupportedException("Already Disposed");

            if (m_PersistanceService_calculated)
                m_PersistanceService.Dispose();

            m_Diposed = true;
        }

		#endregion
    }
}
